import * as util from 'util';
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';

export const fsAccess = util.promisify(fs.access);
export const fsReaddir = util.promisify(fs.readdir);
export const fsStat = util.promisify(fs.stat);

async function readFileList(dir: string, filesList: string[] = []) {
    const files = await fsReaddir(dir);
    for (let item of files) {
        var fullPath = path.join(dir, item);
        const stat = await fsStat(fullPath);
        if (stat.isDirectory()) {
            await readFileList(path.join(dir, item), filesList); //递归读取文件
        } else {
            filesList.push(fullPath);
        }
    }
    return filesList;
}

export const fsReadAllDir = (filepath: string) => {
    const filesList: string[] = [];
    return readFileList(filepath, filesList);
};

export function streamMd5(filepath: string) {
    return new Promise<string>((resolve, reject) => {
        const md5sum = crypto.createHash('md5');
        const stream = fs.createReadStream(filepath, {highWaterMark: Math.pow(2, 16)});
        stream.on('data', (chunk) => {
            md5sum.update(chunk);
        });
        stream.on('end', () => {
            const md5Str = md5sum.digest('hex');
            stream.destroy();
            md5sum.destroy();
            resolve(md5Str);
        });
        stream.on('error', reject);
    });
}

export function sleep(timeout: number) {
    return new Promise(resolve => {
        setTimeout(resolve, timeout);
    });
}
